const bcrypt = require('bcryptjs');
const jwt = require('jsonwebtoken');
const User = require('../models/user.model');

const resolvers = {
    // 查询解析器
    me: async (args, context) => {
        if (!context.user) {
            throw new Error('未认证');
        }
        return context.user;
    },

    user: async ({ id }) => {
        try {
            const user = await User.findById(id);
            if (!user) {
                throw new Error('用户不存在');
            }
            return user;
        } catch (err) {
            throw new Error('获取用户失败');
        }
    },

    users: async () => {
        try {
            return await User.find({});
        } catch (err) {
            throw new Error('获取用户列表失败');
        }
    },

    // 变更解析器
    register: async ({ name, email, password, age }) => {
        try {
            // 检查邮箱是否已存在
            const existingUser = await User.findOne({ email });
            console.log('existingUser',existingUser);
            if (existingUser) {
                throw new Error('邮箱已被注册');
            }

            // 加密密码
            const hashedPassword = await bcrypt.hash(password, 12);

            // 创建新用户
            const user = new User({
                name,
                email,
                password: hashedPassword,
                age
            });

            await user.save();

            // 生成 token
            const token = jwt.sign(
                { userId: user.id },
                process.env.JWT_SECRET,
                { expiresIn: '24h' }
            );

            return {
                token,
                user
            };
        } catch (err) {
            throw new Error('注册失败: ' + err.message);
        }
    },

    login: async ({ email, password }) => {
        try {
            const user = await User.findOne({ email });
            if (!user) {
                throw new Error('用户不存在');
            }

            const isValid = await bcrypt.compare(password, user.password);
            if (!isValid) {
                throw new Error('密码错误');
            }

            const token = jwt.sign(
                { userId: user.id },
                process.env.JWT_SECRET,
                { expiresIn: '24h' }
            );

            return {
                token,
                user
            };
        } catch (err) {
            throw new Error('登录失败: ' + err.message);
        }
    },

    updateUser: async (args, context) => {
        if (!context.user) {
            throw new Error('未认证');
        }

        try {
            const updates = {};
            if (args.name) updates.name = args.name;
            if (args.age) updates.age = args.age;
            if (args.email) updates.email = args.email;

            const user = await User.findByIdAndUpdate(
                context.user.id,
                updates,
                { new: true }
            );

            return user;
        } catch (err) {
            throw new Error('更新用户失败');
        }
    },

    deleteUser: async (args, context) => {
        if (!context.user) {
            throw new Error('未认证');
        }

        try {
            await User.findByIdAndDelete(context.user.id);
            return true;
        } catch (err) {
            throw new Error('删除用户失败');
        }
    }
};

module.exports = resolvers; 